using System.Net;
using System.Net.Sockets;
using System.Text;

var listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 9000);
try
{
    listener.Start();
    Console.WriteLine($"服务已启动 :9000");

    while (true)
    {
        using var client = listener.AcceptTcpClient();
        using var stream = client.GetStream();

        var requestBytes = new byte[4096];
        var bytesRead = stream.Read(requestBytes, 0, requestBytes.Length);

        var request = Encoding.UTF8.GetString(requestBytes, 0, bytesRead);
        Console.WriteLine($"接收到来自客户端的请求：{request}");

        var response = "服务器已收到请求。";
        var responseBytes = Encoding.UTF8.GetBytes(response);

        stream.Write(responseBytes, 0, responseBytes.Length);
        Console.WriteLine($"已发送响应给客户端：{response}");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"发生异常：{ex.Message}");
}
finally
{
    listener.Stop();
    Console.WriteLine("服务器已停止。");
}